﻿using System;
using System.Collections.Generic;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using Kiiro.SiteDefinition.MasterPage;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using PortalFileUrls = Kiiro.Common.Utility.Constants.PortalFileUrls;

namespace Kiiro.SiteDefinition.PortalPages
{
    public partial class NewUser : BasePage
    {
        #region Properties
        public new User User
        {
            get;
            set;
        }

        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) v2CustomFieldCollection; }
        }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachments; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public FormButtons Buttons
        {
            get { return ( FormButtons ) v2FormButtons; }
        }
        #endregion

        #region Page Events
        protected override void OnInit ( EventArgs e )
        {
            base.OnInit ( e );
            CustomFields.ControlMode = SPControlMode.New;
            Buttons.SaveButton.ControlMode = SPControlMode.New;
            Buttons.CancelButton.ControlMode = SPControlMode.New;
            NavigationSub.DeleteButton.ControlMode = SPControlMode.New;
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            Attachments.MaxLength = 1;
            Attachments.FileFormat = "jpg|png";

            CustomFields.EntityType = typeof ( User );
            CustomFields.Title = "Additional Information";

            SPContext context = CustomModel.GetCustomFieldsContext ( typeof ( User ), ItemId, Context, SiteCollectionId, ServerRelativeUrl );
            context.FormContext.FormMode = SPControlMode.New;

            Buttons.SaveButton.ItemContext = context;
            Buttons.SaveButton.RenderContext = context;

            Buttons.CancelButton.ItemContext = context;
            Buttons.CancelButton.RenderContext = context;
            Buttons.CancelButton.RedirectUrl = Cancel ( );

            litTitle.Text = "New User";

            if ( !PermissionBitsUsers [ 0 ] || !CurrentUser.IsAdministrator )
            {
                Response.Redirect ( String.Format ( "{0}/default.aspx", ServerRelativeUrl ) );
            }
            else
            {
                if ( !IsPostBack )
                {
                    //Authentication.Visible = SPHelpers.IsFormsBasedAuthenticationEnabled ( SiteCollectionId, ServerRelativeUrl );
                    if (!SPHelpers.IsFormsBasedAuthenticationEnabled ( SiteCollectionId, ServerRelativeUrl ) )
                    {
                        Authentication.Attributes.Add("style", "display:none");
                        pnlForms.Attributes.Add("style","display:none");
                    }
                    bool smtpServerExists = SetupModel.GetSMTPServerExists ( SiteCollectionId, ServerRelativeUrl );

                    pnlEmailNotifications.Visible = smtpServerExists; ;
                    chkReceiveEmail.Checked = smtpServerExists;
                    rbAuthentication.SelectedValue = "AD";
                }
            }
        }
        #endregion

        #region Methods
        internal override bool Save ( )
        {
            if ( PermissionBitsUsers [ 0 ] )
            {
                bool isForms = rbAuthentication.SelectedValue == "Forms";
                string login = isForms ? txtLogin.Text : txtADLogin.Text;
                User existingUser = UserModel.GetUserByLogin ( login, SiteCollectionId, ServerRelativeUrl );
                List<Attachment> attachments = Attachments.GetAttachments ( );

                User = new User
                {
                    AddToAllProjects = chkAddToAllProjects.Checked,
                    CreatedBy = existingUser != null ? existingUser.CreatedBy : CurrentUser,
                    CreatedDate = existingUser != null ? existingUser.CreatedDate : DateTime.Now,
                    EditType = existingUser != null ? EditType.Updated : EditType.Created,
                    Email = txtEmail.Text,
                    FirstName = txtFirstName.Text,
                    Id = existingUser != null ? existingUser.Id : -1,
                    IsAdministrator = ckIsAdministrator.Checked,
                    IsNonExplicitMember = false,
                    ManageProjectsOnly = !ckIsAdministrator.Checked && ckManageProjects.Checked,
                    IM = txtIM.Text,
                    IMClient = txtIMClient.Text,
                    LastName = txtLastName.Text,
                    CompanyName = txtCompanyName.Text,
                    Login = login,
                    IsFormsUser = isForms,
                    Password = isForms ? txtPassword.Text : null,
                    PhoneNumber = txtPhoneNumber.Text,
                    ReceiveEmailNotification = chkReceiveEmail.Checked,
                    ServerRelativeUrl = ServerRelativeUrl,
                    SiteCollectionId = SiteCollectionId,
                    Title = txtTitle.Text,
                    ModifiedBy = CurrentUser,
                    ModifiedDate = DateTime.Now,
                    CustomFieldNamesAndValues = CustomFields.HarvestCustomFieldValues ( ),
                    PictureBytes = attachments.Count > 0 ? attachments [ 0 ].Bytes : null,
                    PictureUrl = attachments.Count > 0 ? attachments [ 0 ].FileName : null
                };

                if ( isForms )
                {
                    if ( txtPassword.Text != txtConfirmPassword.Text )
                        User.PasswordMessage.Add ( new ValidationMessage ( ValidationSeverity.Validation, "Password Confirmation does not match." ) );
                }
                else
                {
                    if ( UserModel.GetADUser ( User.Login ) == null )
                        User.LoginMessage.Add ( new ValidationMessage ( ValidationSeverity.Validation, "Could not find a matching domain user for the provided login name." ) );
                }

                UserModel.Save ( User, SiteCollectionId, ServerRelativeUrl );

                if ( User.IsValid ( ) )
                    Response.Redirect ( Cancel ( ) );
                else
                    ListErrors ( );
            }
            else
            {
                Response.Redirect ( String.Format ( "{0}{1}", ServerRelativeUrl, PortalFileUrls.UserAll ) );
            }
            return true;
        }

        internal override string Cancel ( )
        {
            return String.Format ( "{0}{1}", ServerRelativeUrl, PortalFileUrls.UserAll );
        }

        private void ListErrors ( )
        {
            ErrorsList errorsList = KiiroMaster.V2ErrorsList;
            errorsList.ErrorMessages.Add ( "There are some submission errors with the form. Errors will be shown in red below the fields." );

            lblPhoneNumberMessage.Text = FormattingHelpers.GetErrorMessageText ( User.PhoneNumberMessage );
            lblPhoneNumberMessage.Visible = !string.IsNullOrEmpty ( lblPhoneNumberMessage.Text );

            lblTitleMessage.Text = FormattingHelpers.GetErrorMessageText ( User.TitleMessage );
            lblTitleMessage.Visible = !string.IsNullOrEmpty ( lblTitleMessage.Text );

            lblEmailMessage.Text = FormattingHelpers.GetErrorMessageText ( User.EmailMessage );
            lblEmailMessage.Visible = !string.IsNullOrEmpty ( lblEmailMessage.Text );

            lblIMMessage.Text = FormattingHelpers.GetErrorMessageText ( User.IMMessage );
            lblIMMessage.Visible = !string.IsNullOrEmpty ( lblIMMessage.Text );

            lblIMClientMessage.Text = FormattingHelpers.GetErrorMessageText ( User.IMClientMessage );
            lblIMClientMessage.Visible = !string.IsNullOrEmpty ( lblIMClientMessage.Text );

            lblLastNameMessage.Text = FormattingHelpers.GetErrorMessageText ( User.LastNameMessage );
            lblLastNameMessage.Visible = !string.IsNullOrEmpty ( lblLastNameMessage.Text );

            lblFirstNameMessage.Text = FormattingHelpers.GetErrorMessageText ( User.FirstNameMessage );
            lblFirstNameMessage.Visible = !string.IsNullOrEmpty ( lblFirstNameMessage.Text );

            if ( rbAuthentication.SelectedValue == "1" )
            {
                lblLoginMessage.Text = FormattingHelpers.GetErrorMessageText ( User.LoginMessage );
                lblLoginMessage.Visible = !string.IsNullOrEmpty(lblLoginMessage.Text);
            }
            else
            {
                lblADLoginMessage.Text = FormattingHelpers.GetErrorMessageText ( User.LoginMessage );
                lblADLoginMessage.Visible = !string.IsNullOrEmpty(lblADLoginMessage.Text);
            }

            lblPasswordMessage.Text = FormattingHelpers.GetErrorMessageText ( User.PasswordMessage );
            lblPasswordMessage.Visible = !string.IsNullOrEmpty ( lblPasswordMessage.Text );

            lblCompanyNameMessage.Text = FormattingHelpers.GetErrorMessageText ( User.CompanyNameMessage );
            lblCompanyNameMessage.Visible = !string.IsNullOrEmpty ( lblCompanyNameMessage.Text );

            lblIsAdministratorMessage.Text = FormattingHelpers.GetErrorMessageText ( User.IsAdministratorMessage );
            lblIsAdministratorMessage.Visible = !string.IsNullOrEmpty ( lblIsAdministratorMessage.Text );

            lblReceiveEmailMessage.Text = FormattingHelpers.GetErrorMessageText ( User.ReceiveEmailNotificationMessage );
            lblReceiveEmailMessage.Visible = !string.IsNullOrEmpty ( lblReceiveEmailMessage.Text );

            lblAddToAllProjectsMessage.Text = FormattingHelpers.GetErrorMessageText ( User.AddToAllProjectsMessage );
            lblAddToAllProjectsMessage.Visible = !string.IsNullOrEmpty ( lblAddToAllProjectsMessage.Text );

            lblEmailMessage.Text = FormattingHelpers.GetErrorMessageText ( User.EmailMessage );
            lblEmailMessage.Visible = !string.IsNullOrEmpty ( lblEmailMessage.Text );
        }
        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.User/User/NewUser.aspx.cs $
 * 
 * 42    2/08/10 5:04p Camerons
 * 
 * 41    2/08/10 2:28p Camerons
 * 
 * 40    1/25/10 1:17p Camerons
 * 
 * 39    1/12/10 12:03p Camerons
 * 
 * 38    1/11/10 11:51a Camerons
 * 
 * 37    1/07/10 2:40p Camerons
 * 
 * 36    1/07/10 12:28p Camerons
 * 
 * 35    1/06/10 12:39p Camerons
 * 
 * 34    26/11/09 10:35a Camerons
 * 
 * 33    17/11/09 6:46p Camerons
 * 
 * 32    29/10/09 4:42p Camerons
 * 
 * 31    27/10/09 5:35p Camerons
 * Remove IsActive from forms
 * 
 * 30    16/10/09 5:41p Shafia
 * Set Attachments Properties MaxLength, and FileFormat to allow one file
 * and .jpg or .png files only.
 * 
 * 29    15/10/09 5:53p Shafia
 * 
 * 28    15/10/09 11:11a Shafia
 * 
 * 27    15/10/09 11:10a Shafia
 * 
 * 26    15/10/09 10:21a Shafia
 * hide forms panel and related fields when forms provider not enabled.
 * 
 * 25    8/10/09 6:41p Camerons
 * Updates for Server License
 * 
 * 24    10/07/09 7:34p Adamw
 * Case: 288, enhanced the check if ability to add Froms user should be
 * displayed.
 * 
 * 23    1/10/09 3:28p Camerons
 * Load Expanded ADGroups into drop down on NewTeamMember. Create user on
 * demand if selected user doesn't exist.
 * 
 * 22    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 21    30/09/09 1:08p Camerons
 * Implementing UserModel.GetOrCreateUser(). 
 * 
 * 20    28/09/09 10:13a Camerons
 * 
 * 19    25/09/09 1:48p Camerons
 * 
 * 18    25/09/09 9:49a Camerons
 * Updated User.IsAdministrator and User.ManageProjectsOnly to be mutually
 * exclusive
 * 
 * 17    23/09/09 4:46p Camerons
 * Fixed some old code dealing with User.ManageProjects
 * 
 * 16    21/09/09 3:30p Camerons
 * First batch of changes for 1.1.x.x - Security groups update
 * 
 * 15    9/04/09 10:27a Stefanf
 * 
 * 14    9/02/09 10:43a Stefanf
 * 
 * 13    9/01/09 11:37a Stefanf
 * 
 * 12    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/